import 'package:flutter/material.dart';

class Home extends StatelessWidget {
  const Home({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("GridView Demo"),
        actions: [IconButton(onPressed: () {}, icon: Icon(Icons.share))],
      ),
      body: GridViewDemo(),
    );
  }
}

//GridView: 类似于 iOS CollectionView
// gridDelegate: 控制GridView子组件如何排列(layout), SliverGridDelegate是一个抽象类，子类需要通过实现它们来实现具体的布局算法
//SliverGridDelegateWithFixedCrossAxisCount : 横轴为固定数量子元素的layout算法

//crossAxisCount: 2, //横轴子元素的数量, 即多少列

//SliverGridDelegateWithMaxCrossAxisExtent : 横轴子元素为固定最大长度的layout算法,
// maxCrossAxisExtent : 子元素在横轴上的最大长度, GridView的width / maxCrossAxisExtent = 行数

// mainAxisSpacing: 10, //主轴方向的间距
// crossAxisSpacing: 10, //横轴方向 子元素的间距
// childAspectRatio: 1.5 //宽高比

class GridViewDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
        child: Column(
      children: [
        Container(
          height: 200,
          child: _fixedCrossAxisDridView(),
        ),
        Container(
          color: Colors.red,
          height: 100,
        ),
        Container(height: 300, child: _maxCrossAxisGridView())
      ],
    ));
  }

  Widget _fixedCrossAxisDridView() {
    return GridView(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3, //多少列
          mainAxisSpacing: 10, //主轴方向的间距
          crossAxisSpacing: 10, //横轴方向 子元素的间距
          childAspectRatio: 1.5 //宽高比
          ),
      children: [
        Container(color: Colors.amber),
        Container(color: Colors.greenAccent),
        Container(color: Colors.blueAccent),
        Container(color: Colors.yellowAccent),
        Container(color: Colors.redAccent),
        Container(color: Colors.pinkAccent),
        Container(color: Colors.purpleAccent),
        Container(color: Colors.black26),
      ],
      padding: EdgeInsets.all(10),
    );
  }

  Widget _maxCrossAxisGridView() {
    return GridView(
      gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
        maxCrossAxisExtent: 180,
        mainAxisSpacing: 10,
        crossAxisSpacing: 10,
      ),
      padding: EdgeInsets.all(10),
      children: [
        Container(color: Colors.amber),
        Container(color: Colors.greenAccent),
        Container(color: Colors.blueAccent),
        Container(color: Colors.yellowAccent),
        Container(color: Colors.redAccent),
        Container(color: Colors.pinkAccent),
        Container(color: Colors.purpleAccent),
        Container(color: Colors.black26),
      ],
    );
  }
}
